﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MediaLibraryManager
{
	public class MediaFormatProvider : IFormatProvider, ICustomFormatter
	{
		public object GetFormat(Type service)
		{
			if (service == typeof(ICustomFormatter))
				return this;
			else
				return null;
		}

		public string Format(string format, object arg, IFormatProvider provider)
		{
			if (format == null)
				return String.Format("{0}", arg);

			if (format != "ARTIST" && format != "SONG" && format != "LIVEAT")
			{
				if (arg is IFormattable)
					return ((IFormattable)arg).ToString(format, provider);
				else if (arg != null)
					return arg.ToString();
			}

			string s = arg.ToString().ToLower();

			string p = string.Empty;
			if (s.IndexOf('(') >= 0 && s.LastIndexOf(')') >= s.IndexOf('('))
			{
				p = s.Substring(s.IndexOf('(') + 1, s.LastIndexOf(')') - s.IndexOf('(') - 1).Trim();
				s = s.Remove(s.IndexOf('('), s.LastIndexOf(')') - s.IndexOf('(') + 1).Trim();
			}

			StringBuilder result = new StringBuilder();
			string a = string.Empty;

			foreach (string item in s.Split(';'))
			{
				a = item.Trim();
				string[] words = a.Split(' ');

				if (words.Length > 0)
				{
					if (format == "ARTIST")
					{
						result.AppendFormat("{0}{1}",
							result.Length == 0 ? string.Empty : "; ",
							LowerSpecialWords(System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(a)));
					}
					else if (format == "SONG")
					{
						if (words.Length <= 2)
						{
							result.AppendFormat("{0}{1}",
								result.Length == 0 ? string.Empty : "; ",
								System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(a));
						}
						else
						{
							result.AppendFormat("{0}{1}{2}",
								result.Length == 0 ? string.Empty : "; ",
								char.ToUpper(a[0]),
								UpperSpecialWords(a.Substring(1)));
						}
					}
					else if (format == "LIVEAT")
					{

					}
				}
			}

			if (p != string.Empty)
				result.AppendFormat(" ({0})", String.Format(new MediaFormatProvider(), String.Format("{{0:{0}}}", format), p));

			return result.ToString();
		}

		private static string LowerSpecialWords(string s)
		{
			s = Regex.Replace(s, @"\bTo\b", "to");
			s = Regex.Replace(s, @"\bThe\b", "the");
			s = Regex.Replace(s, @"\bDu\b", "du");

			return s;
		}

		private static string UpperSpecialWords(string s)
		{
			s = Regex.Replace(s, @"\bi'm\b", "I'm");
			s = Regex.Replace(s, @"\bmr.\b", "Mr.");

			return s;
		}
	}
}
